
import { gg } from "../Game";
import { GameManager, regGameManager } from "../GameManager";
import { BaseEventDefine } from "../common/BaseEventDefine";

export enum SoundDefine {
    CommonBackgroundMusic = "https://g.alicdn.com/eva-assets/005613904a7fa0e6f307146c80b75300/0.0.1/tmp/0e8f8eb/cps-f0e04606e6b7e971b90f101734298e9dedcc88f2.mp3",
    GameBackgroundMusic = 'https://g.alicdn.com/eva-assets/005613904a7fa0e6f307146c80b75300/0.0.1/tmp/0e8f8eb/cps-f0e04606e6b7e971b90f101734298e9dedcc88f2.mp3',
    TouchButton = "touch_button",
}

const SoundPath = 'sound/'

@regGameManager()
export class SoundManager extends GameManager {
    private _isMute: boolean = true
    private _isPlaying: boolean = false
    private _playingMusic: string = ''

    private cache: Map<string, cc.AudioClip> = new Map()
    constructor() {
        super();
        // const isMuteCache = GameStorage.getItem(`${GameStorage.keyPrefix}_is_mute`)
        // const isMute = isMuteCache === null ? true : JSON.parse(isMuteCache)
        // this._isMute = isMute
        gg.eventTarget.on(BaseEventDefine.PageVisibility, (visible: boolean) => {
            if (visible) {
                console.log('-----恢复音频-----')
                setTimeout(() => {
                    cc.audioEngine.resumeAll()
                    cc.sys['__audioSupport'].context.resume()
                }, 500);
            } else {
                console.log('-----暂停音频-----')
                cc.audioEngine.pauseAll()
                cc.sys['__audioSupport'].context.suspend()
            }
        })
    }

    /**
     * 设置静音
     * @param value 
     */
    setMute(value: boolean) {
        this._isMute = value
        if (this._isMute) {
            cc.audioEngine.stopAllEffects()
            this.stopMusic()
        } else {
            this.playMusic()
        }
        // GameStorage.setItem(`${GameStorage.keyPrefix}_is_mute`, JSON.stringify(value))
    }

    /**
     * 获取静音状态
     * @returns 
     */
    getMute() {
        return this._isMute
    }


    /**
     * 播放音乐
     * @param sound 
     */
    async playMusic(sound: SoundDefine = SoundDefine.CommonBackgroundMusic) {
        if (this._isMute) return
        //相同且正在播的音频 return
        if (this._playingMusic == sound && this._isPlaying) return
        const audioClip = await this.getAudioClip(sound)
        if (audioClip) {
            this.stopMusic()
            cc.audioEngine.playMusic(audioClip, true)
            this._isPlaying = true
            this._playingMusic = sound
        }
    }

    /**
     * 停止音乐
     */
    async stopMusic() {
        this._isPlaying = false
        cc.audioEngine.stopMusic()
    }

    /**
     * 播放音效
     * @param sound 
     * @param loop 
     * @returns 
     */
    async playEffect(sound: SoundDefine, loop: boolean = false) {
        if (this._isMute) return
        const audioClip = await this.getAudioClip(sound)
        if (audioClip) {
            cc.audioEngine.playEffect(audioClip, loop)
        }
        return audioClip
    }

    private getAudioClip(sound: SoundDefine): Promise<cc.AudioClip | null> {
        return new Promise((resolve, reject) => {
            const audioClip = this.cache.get(sound)
            if (audioClip) {
                return resolve(audioClip)
            }
            if (sound.startsWith('http')) {
                cc.assetManager.loadRemote(sound, (err: Error, audioClip: cc.AudioClip) => {
                    if (err) {
                        console.log(`${sound} 音频不存在`)
                        resolve(null)
                    } else {
                        this.cache.set(sound, audioClip)
                        resolve(audioClip)
                    }
                })
            } else {
                cc.resources.load(SoundPath + sound, cc.AudioClip, (err: Error, audioClip: cc.AudioClip) => {
                    if (err) {
                        console.log(`${sound} 音频不存在`)
                        resolve(null)
                    } else {
                        this.cache.set(sound, audioClip)
                        resolve(audioClip)
                    }
                })
            }
        })
    }
}